package com.sunelec.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;


import javax.servlet.http.HttpServletRequest;

/**
* @Author: 郑明利
* @Description: JSON工具类
* @Date: Create in 8:43 2018/04/04
* @Modified By:
*/
public class JSONUtils
{
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /***
     * 将List对象序列化为JSON文本
     */

    public static String aliToJSONString(Object o){
        return JSON.toJSONString(o);
    }


    public static JSONObject receivePost(HttpServletRequest request) throws IOException{

        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        System.out.println(sb.toString());
        return JSONObject.parseObject(sb.toString());
    }

    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
